package com.goods.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.IProductMapper;
import com.goods.business.mapper.IProductStockMapper;
import com.goods.business.service.IProductService;
import com.goods.common.enums.system.CategoryIDEnum;
import com.goods.common.error.SystemCodeEnum;
import com.goods.common.error.SystemException;
import com.goods.common.model.business.Product;
import com.goods.common.model.business.ProductStock;
import com.goods.common.vo.business.ProductStockVO;
import com.goods.common.vo.business.ProductVO;
import com.goods.common.vo.system.PageVO;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Date: 2023/3/6 - 18:07
 * @Author: Hyoung
 * @Description:
 */
@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private IProductStockMapper iProductStockMapper;

    @Autowired
    private IProductMapper iProductMapper;

    @Override
    public void remove(Integer id) {
        Product product = new Product();
        product.setId(Long.valueOf(id));
        product.setStatus(1);
        iProductMapper.updateByPrimaryKeySelective(product);

    }

    @Override
    public void back(Integer id) {
        Product product = new Product();
        product.setId(Long.valueOf(id));
        product.setStatus(2);
        iProductMapper.updateByPrimaryKeySelective(product);

    }

    @Override
    public void publish(Integer id) {
        Product product = iProductMapper.selectByPrimaryKey(id);
        if (Objects.isNull(product)) {
            return;
        }
        product.setStatus(0);
        iProductMapper.updateByPrimaryKey(product);

    }

    @Override
    public PageVO<ProductVO> findProducts(Integer pageNum, Integer pageSize,
                                          Integer status, ProductVO productVO) {
        PageHelper.startPage(pageNum, pageSize);
        Long[] categoryKeys = productVO.getCategoryKeys();
        Integer statusProduct = productVO.getStatus();
        String name = productVO.getName();
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(categoryKeys)) {
            int length = categoryKeys.length;
            criteria.andEqualTo(CategoryIDEnum.getCategory(length), categoryKeys[length - 1]);
        }
        if (!Objects.isNull(status)) {
            criteria.andEqualTo("status", status);
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andLike("name", "%" + name + "%");
        }
        List<Product> productList = iProductMapper.selectByExample(example);

        PageInfo<Product> productPageInfo = new PageInfo<>(productList);

        List<ProductVO> collect = productList.stream().map(product -> {
            ProductVO productVOTemp = new ProductVO();
            BeanUtils.copyProperties(product, productVOTemp);
            return productVOTemp;
        }).collect(Collectors.toList());

        return new PageVO<>(productPageInfo.getTotal(), collect);
    }

    @Override
    public PageVO<ProductStockVO> findAllStocks(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<ProductStock> productStockList = iProductStockMapper.selectAll();
        List<ProductStockVO> collect = productStockList.stream().map(productStock -> {
            ProductStockVO productStockVO = new ProductStockVO();
            BeanUtils.copyProperties(productStock, productStockVO);
            return productStockVO;
        }).collect(Collectors.toList());

        PageInfo<ProductStock> productStockPageInfo = new PageInfo<>(productStockList);

        return new PageVO<>(productStockPageInfo.getTotal(), collect);
    }

    @Override
    public ProductVO findProductById(Integer id) {
        Product product = iProductMapper.selectByPrimaryKey(id);
        ProductVO productVO = new ProductVO();
        BeanUtils.copyProperties(product, productVO);

        Long oneCategoryId = product.getOneCategoryId();
        Long twoCategoryId = product.getTwoCategoryId();
        Long threeCategoryId = product.getThreeCategoryId();
        ArrayList<Long> longs = new ArrayList<>();

        if (!Objects.isNull(oneCategoryId)) {
            longs.add(oneCategoryId);
        }
        if (!Objects.isNull(twoCategoryId)) {
            longs.add(twoCategoryId);
        }
        if (!Objects.isNull(threeCategoryId)) {
            longs.add(threeCategoryId);
        }
        Long[] skuIds = longs.toArray(new Long[longs.size()]);
        productVO.setCategoryKeys(skuIds);
        return productVO;
    }

    @Override
    public void editProduct(Integer id, ProductVO productVO) {
        Product product = iProductMapper.selectByPrimaryKey(id);
        if (!Objects.isNull(product) && product.getStatus() != 2) {
            Product productTemp = new Product();
            BeanUtils.copyProperties(productVO, productTemp);
            productTemp.setId(Long.valueOf(id));
            productTemp.setModifiedTime(new Date());
            iProductMapper.updateByPrimaryKey(productTemp);
        }
    }

    @Override
    @SneakyThrows
    public void deleteProductById(Integer id) {
        Product product = iProductMapper.selectByPrimaryKey(id);

        Example example = new Example(ProductStock.class);
        example.createCriteria().andEqualTo("pNum", product.getPNum());
        ProductStock productStock = iProductStockMapper.selectOneByExample(example);
        if (productStock.getStock() > 0) {
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR, "商品还有库存不能删除");
        }
        iProductMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void addProduct(ProductVO productVO) {
        productVO.setCreateTime(new Date());
        productVO.setModifiedTime(new Date());
        productVO.setStatus(2); // 默认状态
        String pNum = UUID.randomUUID().toString();
        productVO.setPNum(pNum);
        Product product = new Product();
        BeanUtils.copyProperties(productVO, product);
        Long[] categoryKeys = productVO.getCategoryKeys();
        if (!Objects.isNull(categoryKeys) && categoryKeys.length > 0) {
            // TODO 需要优化
            int length = categoryKeys.length;
            switch (length) {
                case 3:
                    product.setThreeCategoryId(categoryKeys[2]);
                case 2:
                    product.setTwoCategoryId(categoryKeys[1]);
                case 1:
                    product.setOneCategoryId(categoryKeys[0]);
                default:
            }
        }
        iProductMapper.insert(product);
        // 添加商品库存
        ProductStock productStock = new ProductStock();
        productStock.setPNum(product.getPNum());
        productStock.setStock(0L);
        iProductStockMapper.insert(productStock);
    }

    @Override
    public PageVO<ProductVO> findProductList(Integer pageNum, Integer pageSize, String categorys, Integer status, String name) {
        PageHelper.startPage(pageNum, pageSize);
        Example exampleProduct = new Example(Product.class);
        Example.Criteria criteria = exampleProduct.createCriteria();
        if (!StringUtils.isEmpty(categorys)) {
            String[] split = categorys.split(",");
            // 有数组越界问题
            int length = split.length;
            criteria.andEqualTo(CategoryIDEnum.getCategory(length), split[length - 1]);
        }
        if (!Objects.isNull(status)) {
            criteria.andEqualTo("status", status);
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andLike("name", "%" + name + "%");
        }


        List<Product> products = iProductMapper.selectByExample(exampleProduct);

        List<ProductVO> collect = products.stream().map(product -> {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            return productVO;
        }).collect(Collectors.toList());
        PageInfo<Product> productPageInfo = new PageInfo<>(products);

        return new PageVO<>(productPageInfo.getTotal(), collect);
    }

    @Override
    public PageVO<ProductStockVO> findProductStocks(Integer pageNum, Integer pageSize, String categorys, String name) {
        PageHelper.startPage(pageNum, pageSize);
        // 查询出所有的商品
        // 通过条件过滤
        Example exampleProduct = new Example(Product.class);
        Example.Criteria criteria = exampleProduct.createCriteria();
        if (!StringUtils.isEmpty(categorys)) {
            String[] split = categorys.split(",");
            int length = split.length;
            criteria.andEqualTo(CategoryIDEnum.getCategory(length), split[length - 1]);
        }
        if (!StringUtils.isEmpty(name)) {
            criteria.andLike("name", "%" + name + "%");
        }
        criteria.andEqualTo("status", 0);


        List<Product> products = iProductMapper.selectByExample(exampleProduct);
        // 转换
        List<ProductStockVO> collect = products.stream().map(product -> {
            ProductStockVO productStockVO = new ProductStockVO();
            BeanUtils.copyProperties(product, productStockVO);
            String pNum = product.getPNum();
            // 关联查询商品的数量
            Example exampleProductStock = new Example(ProductStock.class);
            exampleProductStock.createCriteria().andEqualTo("pNum", pNum);
            ProductStock productStock = iProductStockMapper.selectOneByExample(exampleProductStock);
            // 如果没有数量就显示为0
            if (Objects.isNull(productStock)) {
                productStockVO.setStock(0L);
            } else {
                productStockVO.setStock(productStock.getStock());
            }
            return productStockVO;
        }).collect(Collectors.toList());
        PageInfo<Product> productStockVOPageInfo = new PageInfo<>(products);
        return new PageVO<>(productStockVOPageInfo.getTotal(), collect);
    }
}
